<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`分配权限 - ${roleData?.name || ''}`"
    width="1000px"
    @close="handleClose"
    class="permission-dialog"
  >
    <div class="permission-container" v-loading="loading">
      <!-- 搜索栏 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索权限..."
          prefix-icon="Search"
          clearable
          class="search-input"
        />
        <div class="stats">
          <span class="selected-count">已选择 {{ selectedPermissionIds.length }} 项</span>
          <span class="total-count">共 {{ filteredPermissions.length }} 项权限</span>
        </div>
      </div>

      <!-- 权限卡片网格 -->
      <div class="permissions-grid">
        <div
          v-for="permission in filteredPermissions"
          :key="permission.id"
          :class="[
            'permission-card',
            { 'selected': selectedPermissionIds.includes(permission.id) },
            { 'disabled': permission.status === 0 }
          ]"
          @click="togglePermission(permission)"
        >
          <div class="card-header">
            <div class="permission-info">
              <h4 class="permission-name">{{ permission.name }}</h4>
              <span class="permission-code">{{ permission.code }}</span>
            </div>
            <div class="selection-indicator">
              <el-icon v-if="selectedPermissionIds.includes(permission.id)" class="check-icon">
                <Check />
              </el-icon>
            </div>
          </div>
          <p v-if="permission.description" class="permission-desc">
            {{ permission.description }}
          </p>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredPermissions.length === 0" class="empty-state">
        <el-icon class="empty-icon"><DocumentRemove /></el-icon>
        <p>没有找到匹配的权限</p>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定 ({{ selectedPermissionIds.length }})
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, DocumentRemove, Search } from '@element-plus/icons-vue'
import { getAllPermissions } from '@/api/permission'
import { getRolePermissions, updateRolePermissions, type Role, type Permission } from '@/api/role'

interface Props {
  visible: boolean
  roleData?: Role | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const loading = ref(false)
const allPermissions = ref<Permission[]>([])
const selectedPermissionIds = ref<number[]>([])
const searchKeyword = ref('')

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 过滤后的权限列表
const filteredPermissions = computed(() => {
  if (!searchKeyword.value) {
    return allPermissions.value
  }
  const keyword = searchKeyword.value.toLowerCase()
  return allPermissions.value.filter(permission =>
    permission.name.toLowerCase().includes(keyword) ||
    permission.code.toLowerCase().includes(keyword) ||
    (permission.description && permission.description.toLowerCase().includes(keyword))
  )
})

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible && props.roleData) {
    loadAllPermissions()
    loadRolePermissions()
  }
})

// 加载所有权限
async function loadAllPermissions() {
  try {
    const permissions = await getAllPermissions()
    allPermissions.value = permissions
  } catch (error) {
    console.error('Failed to load permissions:', error)
    ElMessage.error('加载权限列表失败')
  }
}

// 加载角色权限
async function loadRolePermissions() {
  if (!props.roleData) return

  try {
    const permissions = await getRolePermissions(props.roleData.id)
    selectedPermissionIds.value = permissions.map(p => p.id)
  } catch (error) {
    console.error('Failed to load role permissions:', error)
    ElMessage.error('加载角色权限失败')
  }
}

// 切换权限选择状态
function togglePermission(permission: Permission) {
  if (permission.status === 0) return // 禁用的权限不能选择

  const index = selectedPermissionIds.value.indexOf(permission.id)
  if (index > -1) {
    selectedPermissionIds.value.splice(index, 1)
  } else {
    selectedPermissionIds.value.push(permission.id)
  }
}

// 提交权限分配
async function handleSubmit() {
  if (!props.roleData) return

  loading.value = true
  try {
    await updateRolePermissions(props.roleData.id, {
      permission_ids: selectedPermissionIds.value
    })
    ElMessage.success('权限分配成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('Failed to update role permissions:', error)
    ElMessage.error('权限分配失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
function handleClose() {
  dialogVisible.value = false
  selectedPermissionIds.value = []
  allPermissions.value = []
  searchKeyword.value = ''
}

// 初始化
onMounted(() => {
  loadAllPermissions()
})
</script>

<style scoped>
/* 对话框基础样式 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  padding: 24px 32px;
  margin: 0;
  border-bottom: none;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #fff;
}

:deep(.el-dialog__headerbtn) {
  top: 24px;
  right: 32px;
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  transition: all 0.3s ease;
}

:deep(.el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

:deep(.el-dialog__close) {
  color: #fff;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding: 24px;
  background: #f8fafc;
}

.permission-container {
  min-height: 500px;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
}

/* 搜索区域 */
.search-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 1px solid #e2e8f0;
}

.search-input {
  width: 300px;
}

:deep(.search-input .el-input__wrapper) {
  border-radius: 12px;
  border: 2px solid #e2e8f0;
  transition: all 0.3s ease;
}

:deep(.search-input .el-input__wrapper:hover) {
  border-color: #667eea;
}

:deep(.search-input .el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.stats {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 14px;
}

.selected-count {
  color: #667eea;
  font-weight: 600;
}

.total-count {
  color: #64748b;
}

.dialog-footer {
  text-align: right;
  padding: 20px 24px;
  background: #fff;
  border-top: 1px solid #e2e8f0;
  /* margin: 0 -24px -24px -24px; */
}

/* 权限卡片网格 */
.permissions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  padding: 24px;
  max-height: 400px;
  overflow-y: auto;
}

.permission-card {
  background: #fff;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.permission-card:hover {
  border-color: #667eea;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
  transform: translateY(-2px);
}

.permission-card.selected {
  border-color: #667eea;
  background: linear-gradient(135deg, #f0f4ff 0%, #e8f0fe 100%);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
}

.permission-card.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f8fafc;
}

.permission-card.disabled:hover {
  border-color: #e2e8f0;
  box-shadow: none;
  transform: none;
}

.card-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 8px;
}

.permission-info {
  flex: 1;
}

.permission-name {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 4px 0;
  line-height: 1.4;
}

.permission-card.selected .permission-name {
  color: #667eea;
}

.permission-code {
  font-size: 12px;
  color: #667eea;
  background: linear-gradient(135deg, #f0f4ff 0%, #e8f0fe 100%);
  padding: 4px 8px;
  border-radius: 6px;
  font-family: 'SF Mono', 'Monaco', 'Menlo', monospace;
  font-weight: 600;
  border: 1px solid #c7d2fe;
}

.permission-card.selected .permission-code {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-color: #667eea;
}

.selection-indicator {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 2px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-left: 12px;
}

.permission-card.selected .selection-indicator {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
}

.check-icon {
  color: #fff;
  font-size: 14px;
}

.permission-desc {
  font-size: 13px;
  color: #64748b;
  line-height: 1.5;
  margin: 0;
}

.permission-card.selected .permission-desc {
  color: #475569;
}
/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 24px;
  color: #64748b;
}

.empty-icon {
  font-size: 48px;
  color: #cbd5e1;
  margin-bottom: 16px;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
}

/* 滚动条样式 */
.permissions-grid::-webkit-scrollbar {
  width: 8px;
}

.permissions-grid::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

.permissions-grid::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #cbd5e1 0%, #94a3b8 100%);
  border-radius: 4px;
  transition: all 0.3s ease;
}

.permissions-grid::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 底部按钮样式 */
:deep(.dialog-footer .el-button) {
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.3s ease;
  border-width: 2px;
}

:deep(.dialog-footer .el-button--default) {
  background: #fff;
  border-color: #e2e8f0;
  color: #475569;
}

:deep(.dialog-footer .el-button--default:hover) {
  background: #f8fafc;
  border-color: #667eea;
  color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

:deep(.dialog-footer .el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

:deep(.dialog-footer .el-button--primary:hover) {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
  border-color: #5a67d8;
  transform: translateY(-1px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

:deep(.dialog-footer .el-button--primary:active) {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 响应式适配 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto !important;
  }

  .permissions-grid {
    grid-template-columns: 1fr;
    padding: 16px;
  }

  .search-section {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .stats {
    justify-content: center;
  }
}
</style>
